<template>
  <el-upload
    drag
    :multiple="false"
    :action="actionUrl"
    :headers="headers"
    :on-success="onSuccess"
    :before-upload="onBeforeUpload"
    :show-file-list="false"
    class="upload"
    :on-change="handleOnChange"
    :on-progress="onProgress"
    :disabled="loading"
  >
    <template v-if="!path">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将图片拖到此处，或 <em>点击上传</em></div>
    </template>
    <template v-else>
      <img
        style="width: 100%; height: 100%; object-fit: contain"
        :src="filePath + path"
      />
      <div class="close" @click.stop="onRemove">
        <i class="el-icon-error"></i>
      </div>
    </template>
    <template #tip>
      <div class="el-upload__tip">
        <el-progress
          v-if="loading"
          :percentage="percentage"
          status="success"
          class="w-200"
        ></el-progress>
        <slot name="tip"></slot>
      </div>
    </template>
  </el-upload>
</template>

<script>
import { getToken } from "@/utils/auth";
export default {
  name: "CImgUpload",
  props: {
    path: {
      type: String,
      default: "",
    },
    actionUrl: {
      type: String,
      default: "",
    },
    beforeUpload: {
      type: Function,
      default: () => {},
    },
  },
  computed: {
    headers() {
      let token = getToken();
      return token ? { Authorization: token } : {};
    },
  },
  data() {
    return {
      filePath,
      loading: false,
      percentage: 0,
    };
  },
  methods: {
    onSuccess(res, file, fileList) {
      this.$emit("uploadSuccess", res, file, fileList);
    },
    onBeforeUpload(file) {
      const valid = this.beforeUpload(file);
      if (valid === false) {
        this.loading = false;
        this.percentage = 0;
        return false;
      }
    },
    onRemove() {
      this.$emit("remove");
    },
    handleOnChange(file, fileList) {
      this.loading = true;
      if (file.percentage == 100) {
        this.loading = false;
        this.percentage = 0;
      }
    },
    onProgress(file) {
      this.percentage = file.percent;
    },
  },
};
</script>
<style lang="scss" scoped>
.upload {
  position: relative;
}
.close {
  width: 32px;
  height: 32px;
  font-size: 16px;
  color: red;
  position: absolute;
  top: 0;
  right: 0;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
}
.w-200 {
  max-width: 200px;
}
</style>
